package com.shinbada.modules.sys.service;

import com.shinbada.common.ResultCode;
import com.shinbada.common.utils.StringUtils;
import com.shinbada.core.persistence.Page;
import com.shinbada.core.service.CrudService;
import com.shinbada.exception.ServiceException;
import com.shinbada.modules.sys.entity.Post;
import com.shinbada.modules.sys.mapper.PostMapper;
import com.shinbada.modules.sys.reference.PostReferenceService;
import com.shinbada.modules.sys.utils.UserUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Comparator;
import java.util.List;

/**
 * @author initcap
 * @date 2020/10/6 12:41
 */
@Service
@Transactional(readOnly = true)
public class PostService extends CrudService<PostMapper, Post> {

    @Autowired
    private List<PostReferenceService> postReferenceServiceList;

    @Override
    public Post get(String id) {
        return super.get(id);
    }

    @Override
    public List<Post> findList(Post post) {
        return super.findList(post);
    }

    @Override
    public Page<Post> findPage(Page<Post> page, Post post) {
        return super.findPage(page, post);
    }

    @Override
    @Transactional(readOnly = false)
    public void save(Post post) {
        saveBeforeCheck(post);

        // 获取排序号，最末节点排序号+30
        if (StringUtils.isBlank(post.getId())) {
            List<Post> sourcelist = findList(new Post());
            sourcelist.sort(Comparator.comparing(Post::getSort));
            if (CollectionUtils.isNotEmpty(sourcelist)) {
                post.setSort(sourcelist.get(sourcelist.size() - 1).getSort() + 30);
            }
        }

        super.save(post);
    }

    @Override
    @Transactional(readOnly = false)
    public void delete(Post post) {
        postReferenceServiceList.forEach(reference -> {
            if (reference.isReference(post.getId()) && UserUtils.keepReference()) {
                throw new ServiceException(ResultCode.POST_REFERENCE_CAN_NOT_DELETE, ",引用者: " + reference.getName());
            } else if (reference.isReference(post.getId()) && !UserUtils.keepReference()) {
                reference.deleteReference(post.getId());
            }
        });
        super.delete(post);
    }

    private void saveBeforeCheck(Post post) {
        if (checkNameExist(post.getId(), post.getName())) {
            throw new ServiceException(ResultCode.POST_NAME_EXIST);
        }
    }

    private boolean checkNameExist(String id, String name) {
        return mapper.countName(id, UserUtils.getUser().getCompany().getId(), name) > 0;
    }

}
